﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.StaticFiles;
using System.Collections.Generic;

namespace FrameWork
{
   public class TimUseExceptionHandler
   {
       public static void Init(IApplicationBuilder app, List<string> defaultFileNames = null)
       {
            app.UseAuthentication();
            //            app.Map("/ws", SocketRegister.Register);

            if (defaultFileNames != null)
            {
                app.UseDefaultFiles(new DefaultFilesOptions
                {
                    DefaultFileNames = defaultFileNames
                });
            }

            app.UseStaticFiles();

            app.UseStaticFiles(new StaticFileOptions
            {
                ContentTypeProvider = new FileExtensionContentTypeProvider(new Dictionary<string, string>
                {
                    { ".apk","application/vnd.android.package-archive"},
                    { ".nupkg","application/zip"}
                })
            });


            app.UseExceptionHandler(errorApp =>
             {
                 errorApp.Run(async context =>
                 {
                     string str;
                     var error = context.Features.Get<IExceptionHandlerFeature>()?.Error;
                     var code = context.Response.StatusCode;
                     context.Response.StatusCode = 200;

                     if (error?.GetType().Name != "IException")
                     {
                         Log4Help.Error($"{code}错误", error);
                         if (PublicTool.JsonpAction(out var callback))
                         {
                             context.Response.ContentType = "text/plain";
                             var json = await PublicTool.ReturnErrorJsonp("02系统错误,请联系管理员");
                             str = json.Content;
                         }
                         else
                         {
                             context.Response.ContentType = "application/json";
                             var json = await PublicTool.ReturnError("04系统错误,请联系管理员");
                             str = PublicTool.JsonResultToStr(json);
                         }
                     }
                     else
                     {
                         if (PublicTool.JsonpAction(out var callback))
                         {
                             context.Response.ContentType = "text/plain";
                             var json = await PublicTool.ReturnErrorJsonp(error.Message);
                             str = json.Content;
                         }
                         else
                         {
                             var json = await PublicTool.ReturnError(error.Message);
                             str = PublicTool.JsonResultToStr(json);
                         }
                     }
                     await context.Response.WriteAsync(str);
                 });
             });

            app.UseStatusCodePages(errorApp =>
            {
                errorApp.Run(async context =>
                {
                    string str;
                    var code = context.Response.StatusCode;
                    context.Response.StatusCode = 200;

                    if (code == 401)
                    {
                        if (PublicTool.JsonpAction(out var callback))
                        {
                            context.Response.ContentType = "text/plain";
                            var json = await PublicTool.ReturnErrorJsonp("用户未登陆", code);
                            str = json.Content;
                        }
                        else
                        {
                            context.Response.ContentType = "application/json";
                            var json = await PublicTool.ReturnError("用户未登陆", code);
                            str = PublicTool.JsonResultToStr(json);
                        }
                    }
                    else
                    {
                        Log4Help.Error($"{code}错误:{context.Request.Path.Value}");
                        if (PublicTool.JsonpAction(out var callback))
                        {
                            context.Response.ContentType = "text/plain";
                            var json = await PublicTool.ReturnErrorJsonp("03系统错误,请联系管理员");
                            str = json.Content;
                        }
                        else
                        {
                            context.Response.ContentType = "application/json";
                            var json = await PublicTool.ReturnError("01系统错误,请联系管理员");
                            str = PublicTool.JsonResultToStr(json);
                        }
                    }
                    await context.Response.WriteAsync(str);
                });
            });

            app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); });

            app.UseSwagger();
            app.UseSwaggerUI(x =>
            {
                x.SwaggerEndpoint("/swagger/v1/swagger.json", "v1");
                x.RoutePrefix = string.Empty;
            });            
            app.UseCors("AllowCors");
        }
    }
}
